var ybname = '天然气';
var millName; //染厂名称
var millData = [];
var openID;
// var openID='ovC8bs1pQ7YMjKXj60NMy1-DQ-7o'; //测试时使用
var hgS2;
var Judge_plan;
var number=0;

//获取 code 根据code 获取对应的openid
var code = getQueryString("code");
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

$(function () {

    /*设置日期默认值*/
    var etime = new Date();
    //$('#appDateTime').val(formatterSDate(etime));
    $('#appDateTime').val(getDay(0));
    $('#appDateTime02').val(formatterEDate(etime));



    console.log('code=' + code);
    getopenid();
    
    /* setTimeout(function() {
         console.log('1='+ millData);
     }, 1000);*/

});

function getopenid() {
    console.log(
        'https://www.xdfznh.club/wxpadbe/switch/oao/'
        + code);

    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe/switch/oao/'
            + code,
        type: 'get',
        dataType: 'json',
        // 成功回调
        success: function (data) {
            console.log('请求成功');
            openID = data.data;
            console.log('openID=' + openID);
            getmill();
        },
        //失败回调
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //查看错误信息
            console.log('失败回调');
            console.log(XMLHttpRequest.status);
            console.log(XMLHttpRequest.readyState);
            console.log(textStatus);
        }

    })
}

//获取微信号对应的染厂名称
function getmill() {
    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe'
            + '/userMillController/selectMills/'
            + openID,

        type: 'get',
        dataType: 'json',
        success: function (data) {
            console.log(data.length);
            var ID;
            var liNodes = document.getElementsByTagName("input");
            if (data.length == 0) {
                // 关闭当前页面
                alert('当前用户没有权限！');
                CleanupGrid();

            }

            if (data.length > 0) {
                millName = data[0].mill;

                for (var n = 0; n < data.length; n++) {
                    millData[n] = data[n].mill;
                    console.log(data[n].mill);
                }
                ;
                getJurisdiction(); //获取个人查看报表的权限
                getDropDownDate(); // 设置下拉

            }
            ;
        }
    })
};

//获取个人查看报表的权限
function getJurisdiction() {
    console.log('https://www.xdfznh.club/wxpadbe'
        + '/perm/selectBoss/'
        + openID + '/'
        + millName);
    console.log(millName);

    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe'
            + '/perm/selectBoss/'
            + openID + '/'
            + millName,

        type: 'get',
        dataType: 'json',
        success: function (data) {

            if (data.length > 0) {
                millName = data[0].mill;
                var plan = eval('(' + data[0].auth_report + ')');

                if (plan) {
                    Judge_plan = true;
                    getData();
                    getData02();
                    //getsum();
                    //getsum02();
                    mergecell();
                    mergecell02();
                    showColor();
                } else {
                    Judge_plan = false;
                    alert('当前用户没有查看排单计划权限！');
                    CleanupGrid();
                }


                for (var n = 0; n < data.length; n++) {
                    millData[n] = data[n].mill;
                    console.log(data[n].mill);
                }
                ;
                // console.log(millData);
                getDropDownDate(); // 设置下拉

            } else {
                Judge_plan = false;
                alert('当前用户没有查看报表权限！');
                CleanupGrid();
            }
            ;
        }
    })

}


function getData() {

    var data1=document.getElementById("appDateTime").value.substr(0, 10);
    var data2=document.getElementById("appDateTime02").value.substr(0, 10);

    if (timeFn(data1,data2)>31){
        alert('当前查询日期区间大于一个月，不可查询！');
        return;
    }

    console.log('https://www.xdfznh.club/wxpadbe/execute/query/'
        + millName + '/'
        + "call p_GetJTHyield('"
        + document.getElementById("appDateTime").value
        +"','"
        + document.getElementById("appDateTime02").value
        + "')");

    $(".buttom").attr("disabled",true);

    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe/execute/query/'
            + millName + '/'
            + "call P_ProcessOutput('"
            + document.getElementById("appDateTime").value
            +"','"
            + document.getElementById("appDateTime02").value
            + "')",

        type: 'get',
        dataType: 'json',
        success: function (data) {

            $('#waterdetai').datagrid('loadData', data);
            showColor();
            mergecell();
            $(".buttom").attr("disabled",false);
        },
        complete: function(XMLHttpRequest, textStatus) {
            $(".buttom").attr("disabled",false);
        }

    })
}

function getData02() {

    var data1=document.getElementById("appDateTime").value.substr(0, 10);
    var data2=document.getElementById("appDateTime02").value.substr(0, 10);

    if (timeFn(data1,data2)>31){
       //alert('当前查询日期区间大于一个月，不可查询！');
        return;
    }

    console.log('https://www.xdfznh.club/wxpadbe/execute/query/'
        + millName + '/'
        + "call p_varietiesOutPut('"
        + document.getElementById("appDateTime").value
        +"','"
        + document.getElementById("appDateTime02").value
        + "')");

    $(".buttom").attr("disabled",true);

    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe/execute/query/'
            + millName + '/'
            + "call p_varietiesOutPut('"
            + document.getElementById("appDateTime").value
            +"','"
            + document.getElementById("appDateTime02").value
            + "')",

        type: 'get',
        dataType: 'json',
        success: function (data) {

            $('#waterdetai02').datagrid('loadData', data);
            /*showColor();*/
            mergecell02();
            $(".buttom").attr("disabled",false);
        },
        complete: function(XMLHttpRequest, textStatus) {
            $(".buttom").attr("disabled",false);
        }

    })
}

//根据条件改变背景 色
function showColor() {
    $('#waterdetai').datagrid({
        rowStyler: function (index, row) {
            if (row.type == "合") {
                //return 'color:#0080FF ';   //#E0ECFF
                return 'background-color:#E0ECFF ';

            }
        }
    });
}

//合计 工序产量表
function getsum() {
    $('#waterdetai').datagrid({
        showFooter: true,
        onLoadSuccess: function (data) {
            data = data.rows;
            var ps = 0;
            var qty = 0;
            for (let i = 0; i < data.length; i++) {
                ps += data[i].b_ps ? parseFloat(data[i].b_ps) : 0;
                qty += data[i].b_qty ? parseFloat(data[i].b_qty) : 0;

            }
            $(this).datagrid('reloadFooter', [{
                b_date: '合计',
                b_ps: ps.toFixed(0),
                b_qty: qty.toFixed(0),
            }])
        }
    });

}

function getsum02() {
    $('#waterdetai02').datagrid({
        showFooter: true,
        onLoadSuccess: function (data) {
            data = data.rows;
            var ps = 0;
            var qty = 0;
            for (let i = 0; i < data.length; i++) {
                ps += data[i].b_ps ? parseFloat(data[i].b_ps) : 0;
                qty += data[i].b_qty ? parseFloat(data[i].b_qty) : 0;

            }
            $(this).datagrid('reloadFooter', [{
                b_date: '合计',
                b_ps: ps.toFixed(0),
                b_qty: qty.toFixed(0),
            }])
        }
    });

}

//查询事件
function getquery() {
    if (Judge_plan == true) {
        getData();
        getData02();
    }
}

/*查询昨日的日期设置*/
function getYesterday() {
    var etime = new Date();
    $('#appDateTime').val(getDay(-1));
    $('#appDateTime02').val(getDay(-1));

    getquery();
}

/*查询本日的日期设置*/
function getToday() {
    var etime = new Date();

    $('#appDateTime').val(getDay(0));
    $('#appDateTime02').val(getDay(0));

    getquery();
}

/*查询一周的日期设置*/
function getWeekdate() {
    var etime = new Date();
    $('#appDateTime').val(getDay(-7));
    $('#appDateTime02').val(formatterSDate(etime));

    getquery();
}

/*查询一个月的日期设置*/
function getOneMonthdate() {
    var etime = new Date();
    $('#appDateTime').val(getDay(-30));
    $('#appDateTime02').val(formatterSDate(etime));

    getquery();
}

/*查询本月的日期设置*/
function getMonthdate() {
    var etime = new Date();
    $('#appDateTime').val(customSDateMonth(etime));
    $('#appDateTime02').val(formatterSDate(etime));

    getquery();
}


//设置染厂下拉
function getDropDownDate() {
    console.log('2=' + millData);
    hgS2 = new selectSwiper({
        el: '.select_box2',
        mustSelect: true,
        activeIndex: 0,
        data: millData,
        init: function (index) {
            if (index !== -1) {
                $('.btn2').html(this.data[index]);
            }
        },
        okFunUndefind: function () {
            alert('必须选择一项');
        },
        okFun: function (index) {
            $('.btn2').html(this.data[index]);
            millName = $('button').text();
            getJurisdictionmill();

        },
        closeFun: function () {
            console.log('取消');
        },
    });

    $('.btn2').on('click', function () {
        hgS2.openSelectSwiper();

    });
}

//在更换染厂之后  重新刷新数据  并判断个人权限
function getJurisdictionmill() {
    console.log('https://www.xdfznh.club/wxpadbe'
        + '/perm/selectBoss/'
        + openID + '/'
        + millName);

    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe'
            + '/perm/selectBoss/'
            + openID + '/'
            + millName,

        type: 'get',
        dataType: 'json',
        success: function (data) {

            if (data.length > 0) {
                var plan = eval('(' + data[0].auth_report + ')');

                if (plan) {
                    Judge_plan = true;
                    getData();
                    getData02();
                    //getsum();
                    //getsum02();
                    mergecell
                } else {
                    Judge_plan = false;
                    alert('当前用户没有查看排单计划权限！');
                    CleanupGrid();
                }

            } else {
                Judge_plan = false;
                alert('当前用户没有查看报表权限！');
                CleanupGrid();
            }
            ;
        }
    })

}


//合并单元格
function mergecell() {
    $('#waterdetai').datagrid({
        onLoadSuccess: function (data) {
            data = data.rows;
            var data1=data;
            var data2=data;
            var merges=[];
            var ProcessStr="";
            var m=1;
            console.log(data);
            console.log(data1);
            console.log(data2);
            // console.log(data[0].B_ProcessName);
            // console.log(data[4].B_ProcessName);

            for (let i = 0; i < data1.length; i++) {
                console.log(i);
                ProcessStr= data1[i].B_ProcessName;
                for (let j = 0; j < data2.length; j++) {
                    if (ProcessStr == data2[j].B_ProcessName) {
                        merges.splice(i,1)
                        merges.push({
                            index: i,
                            rowspan: m
                        });
                        m=m+1;
                    }
                }
                i=i+m-2;
                m=1;
                console.log(ProcessStr);

            };


            console.log(merges);

            for(var i=0; i<merges.length; i++)
                $('#waterdetai').datagrid('mergeCells',{
                    index:merges[i].index,
                    field:'B_ProcessName',
                    rowspan:merges[i].rowspan
                });
        }
    });

}

//合并单元格
function mergecell02() {
    $('#waterdetai02').datagrid({
        onLoadSuccess: function (data) {
            data = data.rows;
            var data1=data;
            var data2=data;
            var merges=[];
            var ProcessStr="";
            var m=1;
            console.log(data);
            console.log(data1);
            console.log(data2);
            // console.log(data[0].B_ProcessName);
            // console.log(data[4].B_ProcessName);

            for (let i = 0; i < data1.length; i++) {
                ProcessStr= data1[i].colorClothId;
                for (let j = 0; j < data2.length; j++) {
                    if (ProcessStr == data2[j].colorClothId) {
                        merges.splice(i,1)
                        merges.push({
                            index: i,
                            rowspan: m
                        });
                        m=m+1;
                    }
                }
                i=i+m-2;
                m=1;
                console.log(ProcessStr);

            };


            console.log(merges);

            for(var i=0; i<merges.length; i++)
                $('#waterdetai02').datagrid('mergeCells',{
                    index:merges[i].index,
                    field:'colorClothId',
                    rowspan:merges[i].rowspan
                });
        }
    });

}

/*****************************************************************************************/

/*自定义本月日期时间*/
customSDateMonth = function (date) {
    var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
    return date.getFullYear() + '-' + month + '-' + "01" + " " + "07" + ":" + "00";
};

//计算当前日期的前后几天的日期
function getDay(day) {
    var today = new Date();
    var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
    today.setTime(targetday_milliseconds); //注意，这行是关键代码
    var tYear = today.getFullYear();
    var tMonth = today.getMonth();
    var tDate = today.getDate();
    tMonth = doHandleMonth(tMonth + 1);
    tDate = doHandleMonth(tDate);
    return tYear + "-" + tMonth + "-" + tDate;  // + " " + "07" + ":" + "00"
}

function doHandleMonth(month) {
    var m = month;
    if (month.toString().length == 1) {
        m = "0" + month;
    }
    return m;
}

/******************************************************************************************/

/*设置时间格式*/
function add0(m) {
    return m < 10 ? '0' + m : m
}

function format(shijianchuo) {
//shijianchuo是整数，否则要parseInt转换
    var time = new Date(shijianchuo);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
}

formatterSDate = function (date) {
    var day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
    var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
    return date.getFullYear() + '-' + month + '-' + day /*+ " " + "07" + ":" + "00"*/;
};

formatterEDate = function (date) {
    var day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
    var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
    var hor = date.getHours() > 9 ? date.getHours() : "0" + date.getHours();
    var min = date.getMinutes() > 9 ? date.getMinutes() : "0" + date.getMinutes();
    ;
    var sec = date.getSeconds();
    return date.getFullYear() + '-' + month + '-' + day /*+ " " + hor + ":" + "00"*/;
};

/*****************************************************************************************/



/*计算两个时间差*/
function timeFn(d1,d2) {
//di作为一个变量传进来
//如果时间格式是正确的，那下面这一步转化时间格式就可以不用了
    var dateBegin = new Date(d1.replace(/-/g, "/"));//将-转化为/，使用new Date
    var dateEnd =  new Date(d2.replace(/-/g, "/"));//将-转化为/，使用new Date
    var dateDiff = dateEnd.getTime() - dateBegin.getTime();//时间差的毫秒数
    var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000));//计算出相差天数
    var leave1=dateDiff%(24*3600*1000) //计算天数后剩余的毫秒数
    var hours=Math.floor(leave1/(3600*1000))//计算出小时数
//计算相差分钟数
    var leave2=leave1%(3600*1000) //计算小时数后剩余的毫秒数
    var minutes=Math.floor(leave2/(60*1000))//计算相差分钟数
//计算相差秒数
    var leave3=leave2%(60*1000) //计算分钟数后剩余的毫秒数
    var seconds=Math.round(leave3/1000)
    //console.log(" 相差 "+dayDiff+"天 "+hours+"小时 "+minutes+" 分钟"+seconds+" 秒")
    //console.log(dateDiff+"时间差的毫秒数",dayDiff+"计算出相差天数",leave1+"计算天数后剩余的毫秒数"
    //   ,hours+"计算出小时数",minutes+"计算相差分钟数",seconds+"计算相差秒数");

    return Math.abs(dayDiff);
}


//清空两个网格中的数据
function  CleanupGrid(){
    var data=[];
    $('#waterdetai').datagrid('loadData', data);
    $('#waterdetai02').datagrid('loadData', data);
}